#include "qyklabel.h"
#include <QPainter>
#include "YK16GrayImage.h"

using namespace std;

qyklabel::qyklabel(QWidget *parent)
	: QLabel(parent)
{
	m_pYK16Image = NULL;
	//this->width();
	//m_Rt = this->rect();
	m_bDirection = false; // = hor
	connect(this, SIGNAL(Mouse_Pressed()), this, SLOT(ReDraw()));

	//m_dspQImage = QImage()
}

qyklabel::~qyklabel()
{
}

void qyklabel::SetLineDirection(bool bDirection)
{
	m_bDirection = bDirection;
	update();
}

void qyklabel::mouseMoveEvent( QMouseEvent *ev )
{
	//this->x	= ev->x();
	//this->y = ev->y();
	//emit Mouse_Pos();
}

void qyklabel::mousePressEvent( QMouseEvent *ev )
{
	this->x	= ev->x();
	this->y = ev->y();
	emit Mouse_Pressed();
}

void qyklabel::leaveEvent( QEvent * )
{
	//emit Mouse_Left();
}

void qyklabel::paintEvent( QPaintEvent * )
{
	QPainter painter(this);
	
	painter.setPen( QPen(Qt::black, 2));
	QRect TargetRt = rect();	
	painter.drawRect(TargetRt);

	if (!m_dspQImage.isNull())
	{	
		//printf("dspQImage is not NULL\n");
		painter.drawImage(TargetRt,m_dspQImage); //it Works!\		
		m_crntTime = QTime::currentTime();
	}

	if (m_pYK16Image != NULL)
	{		
		painter.drawImage(TargetRt,m_pYK16Image->m_QImage); //it Works!
		
	}

	if (x> 0 && y>0)
	{
		painter.setPen(QPen(Qt::red, 1, Qt::DotLine));
		if (m_bDirection == false)
		{			
			painter.drawLine(QPoint(0,y),QPoint(width()-1, y));
		}

		if (m_bDirection == true)
		{
			painter.drawLine(QPoint(x,0),QPoint(x, height()-1));
		}	
	}
}

void qyklabel::SetBaseImage( YK16GrayImage* pYKImage )
{
	if (pYKImage->m_pData != NULL && !pYKImage->m_QImage.isNull())
		m_pYK16Image = pYKImage;
}



void qyklabel::ConvertAndCopyPoints(vector<QPoint>& vSrcPoint, int iDataWidth, int iDataHeight)
{
	m_vPt.clear();	

	int dspWidth = this->width();
	int dspHeight = this->height();


	vector<QPoint>::iterator it;

	for (it = vSrcPoint.begin() ; it != vSrcPoint.end() ; it++)
	{
		QPoint tmpDspPt = Data2View((*it),dspWidth, dspHeight, iDataWidth, iDataHeight);
		m_vPt.push_back(tmpDspPt);
	}
}


QPoint qyklabel::View2Data(QPoint viewPt, int viewWidth, int viewHeight, int dataWidth, int dataHeight)
{
	double fZoomX = viewWidth / (double)dataWidth;
	double fZoomY = viewHeight / (double)dataHeight;

	QPoint dataPt;
	dataPt.setX(qRound(viewPt.x() / fZoomX));
	dataPt.setY(qRound(viewPt.y() / fZoomY));

	return dataPt;
}

QPoint qyklabel::Data2View(QPoint dataPt, int viewWidth, int viewHeight, int dataWidth, int dataHeight)
{
	double fZoomX = viewWidth / (double)dataWidth;
	double fZoomY = viewHeight / (double)dataHeight;

	QPoint viewPt;
	viewPt.setX(qRound(dataPt.x() * fZoomX));
	viewPt.setY(qRound(dataPt.y() * fZoomY));

	return viewPt;

}

void qyklabel::SetDrawPointToggle(bool bToggle )
{
	if (bToggle)
		m_bDrawPoints = true;
	else
		m_bDrawPoints = false;


	update();
}

void qyklabel::ReDraw()
{
	update();
}

